import json

from models.setting_models.setting_model import TaskCategory
from utils.db_util import CreateEngine
from enumobjects.general_enum import YesOrNoEnum
from utils.guid_util import GUIDUtil
from utils.common_util import CommonUtil
import logging


class SettingBLL(object):
    @classmethod
    def init_site_settings(cls, json_path):
        session = CreateEngine().get_engine()
        try:
            settings = json.loads(open(json_path, "r").read())
            task_categories = settings["site"]["task_categories"]
            task_id_list = [int(i) for i in task_categories.keys()]
            task_list = session.query(TaskCategory.task_category_id).filter(
                TaskCategory.task_category_id.in_(task_id_list),
                TaskCategory.is_delete == YesOrNoEnum.NO.value
            ).all()
            task_query_id_list = [int(t[0]) for t in task_list]
            add_list = []
            session.begin(subtransactions=True)
            for idx, (cat, handler) in task_categories.items():
                idx = int(idx)
                if idx not in task_query_id_list:
                    task_info = TaskCategory(**{
                        'task_category_id': idx,
                        'guid': str(GUIDUtil.generate()),
                        'name': cat,
                        'handler': handler,
                        'create_time': CommonUtil.get_timestamp()
                    })
                    add_list.append(task_info)
            if add_list:
                logging.info("初始化项目类型成功")
                session.add_all(add_list)
                session.commit()
            session.remove()
            logging.info("初始化项目类型")

        except Exception as ex:
            message = "初始化项目类型错误，原因是：%s" % str(ex)
            session.rollback()
            session.remove()
            logging.info(message)